package com.training.plugins;

import java.io.File;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.codehaus.plexus.archiver.zip.ZipArchiver;
import org.codehaus.plexus.util.FileUtils;

/**
 * Zips up the output directory.
 * @goal zip
 * @phase package
 */
public class ZipMojo extends AbstractMojo
{
    /**
     * The Zip archiver.
     * @component role="org.codehaus.plexus.archiver.Archiver" role-hint="zip"
     */
    private ZipArchiver zipArchiver;

    /**
     * Directory containing the build files.
     * @parameter expression="${project.build.directory}"
     */
    private File buildDirectory;

    /**
     * Base directory of the project.
     * @parameter expression="${basedir}"
     */
    private File baseDirectory;

    /**
     * A set of file patterns to include in the zip.
     * @parameter
     */
    private String[] includes;

    /**
     * A set of file patterns to exclude from the zip.
     * @parameter
     */
    private String[] excludes;

    /**
     * The name of the output zip file.
     * @parameter expression="${zipfile}" default-value="target/output.zip"
     */
    private String zipfile;

    public void execute()
        throws MojoExecutionException
    {
        try {
            FileUtils.mkdir( buildDirectory.getAbsolutePath() );
            zipArchiver.addDirectory( buildDirectory, 
            	includes == null ? new String[] {"**/**"} : includes, 
            	excludes == null ? new String[] {"**/output.zip"} : excludes );
            zipArchiver.setDestFile( new File( baseDirectory, zipfile ) );
            zipArchiver.createArchive();
        } catch( Exception e ) {
            throw new MojoExecutionException( "Could not zip", e );
        }
    }
}
